from common.models import NameSlugModel, DateAwareModel, MyImageModel, UserOwnedModel
from datetime import datetime
from django.contrib.gis.db import models
from django.db import models
from reviews.models import Dish
from tagging.models import Tag

# Create your models here.

class List(NameSlugModel, DateAwareModel, UserOwnedModel):
    dishes = models.ManyToManyField(Dish, blank=True, through='ListMembership')

class ListMembership(DateAwareModel):
    dish = models.ForeignKey(Dish)
    list = models.ForeignKey(List)

    # def __unicode__(self):
        # return self.dish.name + ' ranked #' + str(self.rank) + ' in ' + str(self.ordering.tag.name)

    def save(self, *args, **kwargs):
        """
        Used to update Dish object's last_added_to_list fields
        """
        self.dish.last_added_to = self.list.id
        self.dish.last_added_date_time = datetime.now()
        self.dish.save()

        super(ListMembership, self).save(*args, **kwargs)

class Sorting(DateAwareModel, UserOwnedModel):
    end_comment = models.TextField(max_length=5000, blank=True)
    dishes = models.ManyToManyField(Dish, through='Item')
    intro_comment = models.TextField(max_length=5000, blank=True)
    is_master = models.BooleanField(default=False)
    tag = models.ForeignKey(Tag)
    
    # def natural_key(self):
        # return {
                # 'username' : self.user.username, #.replace("'", " & # 8 s "),
                # 'tag' : self.tag.name,
                # 'id' : self.id,
				# 'count': len(self.rank_set.all()),
        # }

    def __init__(self, *args, **kw):
        print "Entering Sorting init..."
        super(Sorting, self).__init__(*args, **kw)
        # print "After super init..."
        if self.pk:
            self._old_sort_order = [d.id for d in self.dishes.all()]
            print "Init Old Sort Order: " + str(self._old_sort_order)
            self._empty_comment_indicator = [d.id for d in Dish.objects.filter(sorting=self, item__comment__exact='')]

    def save(self, *args, **kwargs):
        print "Entering Sorting save..."
        print "Init Sort Order: " + str([d.id for d in self.dishes.all()])
        super(Sorting, self).save(*args, **kwargs)
        # print "After super save..."
        # isNew = False
        # if hasattr(self, '_old_sort_order'):
            # old_items = frozenset(self._old_sort_order)
        # else:
            # old_items = frozenset()
            # isNew = True

        # print "Arguments..."
        # for arg in args:
            # print arg

        # print "Keywords..."
        # for kw in kwargs.keys():
            # print kw, ":", kwargs[kw]

        # new_items = frozenset([d.id for d in self.dishes.all()])
        # print 'new: ' + str(new_items)
        # print 'old: ' + str(old_items)
        # added_items = new_items.difference(old_items)
        # print added_items
        # if hasattr(self, '_empty_comment_indicator'):
             # old_empty_comment_indicator = frozenset(self._empty_comment_indicator)
        # else:
             # old_empty_comment_indicator = frozenset()
        # new_empty_comment_indicator = frozenset([d.id for d in Dish.objects.filter(sorting=self, item__comment__exact='')])
        # new_comments = new_empty_comment_indicator.difference(old_empty_comment_indicator)
        
        # if added_items or new_comments:
            # print 'Creating Sort Delta...'
            # s = SortDelta()
            # s.isNew = isNew
            # s.sorting = self
            # s.items_with_new_comment = ','.join(map(str, new_comments))
            # s.items_added = ','.join(map(str, added_items))
            # s.prev_order = ','.join(map(str, self._old_sort_order))
            # s.new_order = ','.join([str(d.id) for d in self.dishes.all()])
            # s.save()

    def __unicode__(self):
        return self.tag.name + ' sorting ' + '(' + self.user.username + ')'

class Item(DateAwareModel):
    comment = models.TextField(max_length=5000, blank=True)
    dish = models.ForeignKey(Dish)
    sorting = models.ForeignKey(Sorting)
    preference = models.IntegerField() # 1 - bad, 2 - ok, 3 - good
    rank = models.IntegerField(default=1)

    def __unicode__(self):
        return self.dish.name + ' in ' + str(self.sorting.tag.name)

    class Meta:
        unique_together = ("dish", "sorting")
        ordering = ['-rank']
    
    def save(self, *args, **kwargs):
        """
        Used to update Dish object's last_sorted fields
        """
        print "Entering Item save..."
        self.dish.last_sorted_in = self.sorting.id
        self.dish.last_sorted_date_time = datetime.now()
        self.dish.save()
        return super(Item, self).save(*args, **kwargs)

class SortDelta(DateAwareModel):
    # calculated each time a sorting is modified
    sorting = models.ForeignKey(Sorting)
    # isNew = models.BooleanField(default=False)
    items_with_new_comment = models.CommaSeparatedIntegerField(max_length=1000, blank=True)
    items_added = models.CommaSeparatedIntegerField(max_length=1000, blank=True)
    prev_order = models.CommaSeparatedIntegerField(max_length=1000, blank=True)
    new_order = models.CommaSeparatedIntegerField(max_length=1000, blank=True)
